package cn.labbook.bluetooth.util.p645;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Administrator on 2018/12/21.
 */
@Slf4j
public class Protocol645ParseUtils {
    public static Protocol645 parse(byte[] bytes) {
        Protocol645 protocol645 = new Protocol645();
        try {
            ByteBuf byteBuf = Unpooled.copiedBuffer(bytes);

            protocol645.setOrigin1(byteBuf.readByte());

            byte[] add = new byte[6];

            byteBuf.readBytes(add);

            protocol645.setAddress(add);
            protocol645.setOrigin2(byteBuf.readByte());
            protocol645.setControl(byteBuf.readByte());
            protocol645.setL(byteBuf.readByte());

            byte[] data = new byte[protocol645.getL()&0xff];
            byteBuf.readBytes(data);
            protocol645.setData(data);
            protocol645.setCs(byteBuf.readByte());
            protocol645.setTail(byteBuf.readByte());


            if (protocol645.getOrigin1() != 0x68 || protocol645.getOrigin2() != 0x68 || protocol645.getTail() != 0x16) {
                return null;
            }

            byte checkSum = Protocol645Utils.calcCheckSum(protocol645);

            if (protocol645.getCs() != checkSum) {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return protocol645;
    }
}
